
//  SetupUIViewController.m
//  ent
//
//  Created by Tyrion on 5/22/15.
//  Copyright (c) 2015 ND. All rights reserved.
//

#import "SetupUIViewController.h"
#import <Masonry/Masonry.h>
#import "SetupUITableViewCell.h"
#import "SetupData.h"
#import "AppDelegate.h"
#import <AFNetworking/AFURLSessionManager.h>
#import <UIImageView+WebCache.h>

#import "UIView+WindowAlert.h"
#import <MBProgressHUD/MBProgressHUD.h>
#import "SetupData.h"
#import "BizAlertView.h"
#import "CustomAlertView.h"
#import "RequestPostUploadHelper.h"
#define NICKNAME_WORD_LIMIT 10

@implementation SetupUIViewController



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidLoad {
    [super viewDidLoad];
    [self initView ];
}
- (void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [self.navigationController setNavigationBarHidden:NO];

    self.tabBarController.tabBar.hidden = YES;
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStyleBordered target:nil action:nil];
    self.navigationItem.backBarButtonItem = backItem;
//    self.navigationController.navigationBarHidden = YES;
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    
    
    //初始化设置界面数据
    [self initData];

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    self.tabBarController.tabBar.hidden = NO;
    
    //恢复原来状态栏颜色
//    [[UIApplication sharedApplication] setStatusBarStyle: self.oldStatusStyle animated:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
}


#pragma  mark init view

-(void)initView{
    
//    self.title = @"个人资料";
    CGFloat height = CGRectGetHeight(self.view.frame);
    CGFloat width = CGRectGetWidth(self.view.frame);
    
    self.setupTableView = [UITableView new];
    self.setupTableView.delegate = self;
    self.setupTableView.dataSource = self;
    self.setupTableView.frame = CGRectMake(0, 0, width, height);
    self.setupTableView.bounces  = NO;
    self.setupTableView.scrollEnabled = NO;
    [self.view addSubview:self.setupTableView];
    

}

-(void)initData{
    
    self.dataArray1 = [[NSMutableArray alloc] initWithObjects:@"上传图片", nil];
    self.dataArray2 = [[NSMutableArray alloc] initWithObjects:@"昵称", @"性别", @"地区", @"个性签名", @"生日", nil];
    self.valueArray = [[NSMutableArray alloc] initWithObjects:@" ", @" ", @" ", @" ", @" ", nil];
    
//    MUPRestRequestOperationManager * manager = [AppDelegate restDaoManager];
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    NSString * url = [NSString stringWithFormat:@"%@%@", kGetUserBasicInfo, [AppDelegate uid]];
////    __weak __typeof(self)weakself = self;
//    [manager GET:url parameters:nil beforeRequestHandler:nil class:SetupData.class success:^(MUPHTTPRequestOperation *operation, id responseObject) {
//        [hud hide:YES];
//        weakself.setupData = responseObject;
//        NSString *sex = weakself.setupData.sex ? @"男" : @"女";
//        NSArray *tmpArry = [[NSArray alloc] initWithObjects:weakself.setupData.nickName, sex, weakself.setupData.district, weakself.setupData.signature, weakself.setupData.birthday, nil];
//        [weakself.valueArray removeAllObjects];
//        [weakself.valueArray addObjectsFromArray:tmpArry];
//        [weakself.setupTableView reloadData];
//        
//    } failure:^(MUPHTTPRequestOperation *operation, NSError *error) {
//        [hud hide:YES];
//        BizAlertView * alertView = [[BizAlertView alloc] initErrorAlertWithError:error];
//        [alertView show];
//        
//    }];

}

#pragma mark table delegate
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section == 0 || section == 2) {
        
        return 1;
        
    }else{
        
        return 5;
    }
}

#pragma mark 返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"Cell";
    SetupUITableViewCell *cell;
    cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell){
        cell=[[SetupUITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    switch (indexPath.section) {
        case 0:{
            
//            cell.portraitLayer.hidden = NO;
            cell.portraitImageView.hidden = NO;
            cell.valueLabel.text = [self.dataArray1 objectAtIndex:indexPath.row];
            cell.valueLabel.textAlignment = NSTextAlignmentRight;
            [cell setItem:self.setupData];
            break;
        }
            
        default:
            [[cell textLabel]  setText:@"Unknown"];
            
    }
    
    return cell;
}

#pragma mark 设置每个cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 94;
}


#pragma mark 设置section间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 13.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 13)];
    view.backgroundColor = [UIColor colorWithRed:0.86 green:0.86 blue:0.87 alpha:1];
    return view ;
}

#pragma mark 选中某个cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    
    if (indexPath.section == 0) {
        self.sheetForPhoto = [[UIActionSheet alloc] initWithTitle:@"您要上传图片?"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:@"拍照", @"选择已有图片", nil];
        [self.sheetForPhoto showInView:self.view];

    }
}


#pragma mark customAlret delegate
-(void)doAlertConfirm{

    [self.tabBarController setSelectedIndex:0];
    [[AppDelegate  sharecInstance] presentLoginViewController];
}

#pragma mark action sheet delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet == self.sheetForPhoto) {
        if (buttonIndex == actionSheet.cancelButtonIndex)
        {
            return;
        }
        
        if (buttonIndex == 0)
        {
            [self displayImagePickerCamera];
        }
        else if (buttonIndex == 1)
        {
            [self displayImagePickerPhotoLibrary];
        }

    }
}

#pragma mark  camera 相关
// 推出进入图片库
- (void)displayImagePickerPhotoLibrary
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.delegate             = self;
    imagePicker.sourceType           = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.allowsEditing        = YES; // 允许编辑
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    if ([self isKindOfClass:[UIViewController class]])
    {
        // 推出控制器
        [self presentViewController:imagePicker
                           animated:YES
                         completion:nil];
    }
    else
    {
        NSLog(@"不是控制器");
    }
}

// 推出进入照相机
- (void)displayImagePickerCamera
{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    
    imagePicker.delegate             = self;
    imagePicker.sourceType           = UIImagePickerControllerSourceTypeCamera;
    imagePicker.allowsEditing        = YES; // 允许编辑
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    
    if ([self isKindOfClass:[UIViewController class]])
    {
        // 推出控制器
        [self presentViewController:imagePicker
                           animated:YES
                         completion:nil];
    }
    else
    {
        NSLog(@"不是控制器");
    }
}

// 选定某张图片代理
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES
                             completion:nil];
    
    // 获取到了图片
    //    UIImage *tmpImage = [UIImage croppedImageWithImagePickerInfo:info];
    UIImage *tmpImage = [info objectForKey:UIImagePickerControllerEditedImage];
    //图片压缩 138*138
    UIImage *changeSizeImage = [self scaleToSize:tmpImage size:CGSizeMake(138, 138)];
    //上传到后台
    [self uploadPicture:changeSizeImage];

//    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
//    NSLog(@"%@", imageURL);
//    [self uploadPicture:imageURL];
}

#pragma mark 图片压缩
- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

#pragma mark 上传图片方法

-(void)uploadPicture:(UIImage*)image{
//
//    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
//    MUPRestRequestOperationManager * manager = [AppDelegate restDaoManager];
//    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    __weak __typeof(self)weakself = self;
//    [manager POST:kUpdateUserPortrait parameters:nil beforeRequestHandler:nil constructingBodyWithBlock:^(id<MUPMultipartFormData> formData) {
//        
//        [formData appendPartWithFormData:[[AppDelegate uid] dataUsingEncoding:NSUTF8StringEncoding ] name:@"userId"];
//        [formData appendPartWithFileData:imageData name:@"file" fileName:@"portrait.jpg" mimeType:@"image/jpeg"];
//        [formData appendPartWithFileData:imageData name:@"name" fileName:@"portrait" mimeType:@"image/jpeg"];
//        
//    } class: UpdatePortraitRet.class success:^(MUPHTTPRequestOperation *operation, id responseObject) {
//        [hud hide:YES];
//        UpdatePortraitRet *result = responseObject;
//        weakself.setupData.portrait = result.anotherPortrait;
////        [weakself.setupTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
////        [weakself.setupTableView reloadData];
//        BizAlertView * alert = [[BizAlertView alloc] initWithTitle:@"上传成功"  message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//        [alert show];
//
//    } failure:^(MUPHTTPRequestOperation *operation, NSError *error) {
//        [hud hide:YES];
//        BizAlertView * alertView = [[BizAlertView alloc] initErrorAlertWithError:error];
//        [alertView show];
//    }];
    
    NSString *url =  @"http://121.201.63.131:5001/upload";
//    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

//    NSMutableSet *contentTypes = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
//    [contentTypes addObject:@"text/plain"];
//    [contentTypes addObject:@"text/html"];
//    manager.responseSerializer.acceptableContentTypes = contentTypes;
//    [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    NSDictionary *parameters = @{@"foo": @"bar"};
//    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//
//        [formData appendPartWithFileData:imageData name:@"file" fileName:@"portrait.png" mimeType:@"image/jpeg"];
//        
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"Success: %@", responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"Error: %@", error);
//    }];

    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
//    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    NSData* data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
//    NSArray *keys= [params allKeys];
    
    //遍历keys
//    for(int i=0;i<[keys count];i++)
//    {
//        //得到当前key
//        NSString *key=[keys objectAtIndex:i];
//        //如果key不是pic，说明value是字符类型，比如name：Boris
//        if(![key isEqualToString:@"pic"])
//        {
//            //添加分界线，换行
//            [body appendFormat:@"%@\r\n",MPboundary];
//            //添加字段名称，换2行
//            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
//            //添加字段的值
//            [body appendFormat:@"%@\r\n",[params objectForKey:key]];
//        }
//    }
    
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    //设置接受response的data
    if (conn) {
//        mResponseData = [[NSMutableData data] retain];
        NSMutableData *mResponseData =  [NSMutableData data];
        NSLog(@"%@", mResponseData);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"上传成功" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }


}


@end
